package com.bmicpd.gzh.controller;

import com.bmicpd.gzh.pojo.RealTimePushMessagePojo;
import com.bmicpd.gzh.service.RealTimePushMessageService;
import com.bmicpd.gzh.service.RepetitionRemoveService;
import com.bmicpd.gzh.util.UuidUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

/**
 * 实时获取perl微信机器人推送的微信消息
 * @author ytree
 */
@RestController
public class RealTimePushMessageController {

    private Logger logger = LoggerFactory.getLogger(RealTimePushMessageController.class);

    @Value("${ElasticSearch.HOST}")
    private String esHost;

    @Value("${ElasticSearch.PORT}")
    private int esPort;

    @Value("${ElastisSearch.INDEX}")
    private String esIndex;

    @Value("${ElasticSearch.TYPE}")
    private String esType;

    @Autowired
    private RealTimePushMessageService messageService;


    @RequestMapping(value = "/get")
    public String getRealTimePushMessage(HttpServletRequest request) throws IOException {

        String uuid = UuidUtils.getUUID();

        // 存入到elasticSearch中
        TransportClient transportClient = null;
        try{
            transportClient = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddresses(
                    new InetSocketTransportAddress(InetAddress.getByName(esHost), esPort));
        }catch (UnknownHostException e){
            e.printStackTrace();
        }

        // 读取请求内容
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }

        // 将资料解码
        System.out.println(sb.toString());

        // 用于String 转换成 实例对象
        ObjectMapper mapper = new ObjectMapper();
        RealTimePushMessagePojo pushMessagePojo = mapper.readValue(sb.toString(), RealTimePushMessagePojo.class);
        System.out.println(pushMessagePojo.toString());

        if(null == pushMessagePojo.getApp_name()){
            return "ERROR";
        }

        // 公众号文章去重
        RepetitionRemoveService repetitionRemoveService = new RepetitionRemoveService();
        boolean existFlag =
                repetitionRemoveService.removeRepetition(pushMessagePojo, transportClient, esIndex, esType);
        if(!existFlag){

            return "ERROR";
        }


        // 获取dataSource
        Map<String, String> contentMap = messageService.getContent(pushMessagePojo, uuid);

        assert transportClient != null;
        IndexResponse indexResponse = transportClient.prepareIndex(esIndex, esType)
                .setId(uuid)
                .setSource(contentMap)
                .get();
        logger.info("status: " + indexResponse.status());
        logger.info("response: " + indexResponse.toString());

        return "OK";
    }
}
